package com.fzebu.fastboot.uuid;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @author Y-Aron
 * @create 2018-10-08 23:20
 */
public enum SnowFlake {
    /**
     * 实例
     */
    INSTANCE;

    /**
     * 起始的时间戳
     */
    private final static long START_TIME_STAMP = 1560394987585L;

    /**
     * 序列号占用的位数
     */
    private final static long SEQUENCE_BIT = 12L;

    /**
     * 机器标识占用的位数
     */
    private final static long MACHINE_BIT = 5L;

    /**
     * 数据中心占用的位数
     */
    private final static long DATA_CENTER_BIT = 5L;

    /**
     * 序列号最大值
     */
    private final static long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);

    /**
     * 数据中心最大值
     */
    private final static long MAX_DATA_CENTER_NUM = ~(-1L << DATA_CENTER_BIT);

    /**
     * 机器标识
     */
    private final static long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT);

    /**
     * 机器ID偏左移12位
     */
    private final static long MACHINE_LEFT = SEQUENCE_BIT;

    /**
     * 数据中心ID左移17位
     */
    private final static long DATA_CENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;

    /**
     * 时间毫秒左移22位
     */
    private final static long TIME_STAMP_LEFT = SEQUENCE_BIT + MACHINE_BIT + DATA_CENTER_BIT;

    /**
     * 上一次时间戳
     */
    private long lastTimeStamp = -1L;

    /**
     * 序列号
     */
    private long sequence = 0L;

    /**
     * 数据中心
     */
    private final long dataCenterId;

    /**
     * 机器标识
     */
    private final long machineId;

    SnowFlake() {
        RuntimeMXBean runtimemxbean = ManagementFactory.getRuntimeMXBean();
        this.machineId = getMachineNum() & MAX_MACHINE_NUM;
        this.dataCenterId = Long.parseLong(runtimemxbean.getName().split("@")[0]) & MAX_DATA_CENTER_NUM;
    }

    /**
     * 产生下一个ID
     * @return long uuid
     */
    public synchronized long getNextId() {
        // 获取当前时间戳
        long currentTimeStamp = getCurrentTimeStamp();
        // 如果时间戳小于上次时间戳则报错
        if (currentTimeStamp < lastTimeStamp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }
        // 如果时间戳与上次时间戳相同
        if (currentTimeStamp == lastTimeStamp) {
            // 相同毫秒内，序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            // 同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currentTimeStamp = getNextMill();
            }
        } else {
            // 不同毫秒内，序列号置为0
            sequence = 0L;
        }

        lastTimeStamp = currentTimeStamp;

        // 时间戳部分
        return (currentTimeStamp - START_TIME_STAMP) << TIME_STAMP_LEFT
                | dataCenterId << DATA_CENTER_LEFT      // 数据中心部分
                | machineId << MACHINE_LEFT            // 机器标识部分
                | sequence;                            // 序列号部分
    }

    private long getNextMill() {
        long mill = getCurrentTimeStamp();
        while (mill <= lastTimeStamp) {
            mill = getCurrentTimeStamp();
        }
        return mill;
    }

    private long getCurrentTimeStamp() {
        return System.currentTimeMillis();
    }

    /**
     * 获取机器编码
     */
    private long getMachineNum() {
        StringBuilder sb = new StringBuilder();
        Enumeration<NetworkInterface> enumeration = null;
        try {
            enumeration = NetworkInterface.getNetworkInterfaces();
            while (enumeration.hasMoreElements()) {
                NetworkInterface ni = enumeration.nextElement();
                sb.append(ni.toString());
            }
            return sb.toString().hashCode();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return 0;
    }

}